package cn.hhy.hrm.Exception;

import cn.hhy.hrm.util.AjaxResult;
import com.sun.media.jfxmedia.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BasicException.class)
    public AjaxResult BasicExceptionHandler(BasicException e){
        e.printStackTrace();
        log.error("程序员脑子进水了，出错了哦"+e.getCode()+e.getMessage());
        return AjaxResult.me()
                .setSuccess(false)
                .setCode(e.getCode())
                .setMessage(e.getMessage());

    }


    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setCode(ErrorCode.CODE_400_PARAM_VALID.getCode()).setMessage("系统异常，请重试");

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors =e.getBindingResult().getFieldErrors();
        StringBuffer s = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            s.append(fieldError.getDefaultMessage()).append(",");
            
        }
        String msg = s.toString();
        log.error("程序员脑子进水了，出错了哦"+e.getMessage());
        return AjaxResult.me().setSuccess(false).setCode(ErrorCode.CODE_400_PARAM_VALID.getCode()).setMessage(msg);



    }
}
